// CSE 142, Winter 2008, Marty Stepp // // This program demonstrates a "sentinel" value, // a special value that signals the end of user input. // Sentinel loops are an example of a fencepost problem. // // This version of the code uses a constant for the sentinel. import java.util.*; public class Sentinel2 { public static final int SENTINEL = -1; public static void main(String[] args) { Scanner console = new Scanner(System.in); // read first number (place first "post") System.out.print("Enter a number (" + SENTINEL + " to quit): "); int number = console.nextInt(); int sum = 0; // read remaining numbers while (number != SENTINEL) { // add number to sum (place a "wire") sum = sum + number; // read next number (place a "post") System.out.print("Enter a number (" + SENTINEL + " to quit): "); number = console.nextInt(); } System.out.println("The total was " + sum); } }